package org.xml.create.JDOM;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom2.CDATA;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class JDOMTest {

	public static void main(String[] args) {
		try {
			newRSSByJDOM();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static void newRSSByJDOM() throws FileNotFoundException, IOException {
		//1.创建根节点
		Element rss = new Element("rss");
		//为根节点添加属性
		rss.setAttribute("version", "2.0");
		//2.创建一个Document对象,并为其指定根节点
		Document document = new Document(rss);
		Element channel = new Element("channel");
		
		Element title = new Element("title");
		title.setText("百度最新国内新闻");
		channel.addContent(title);
		
		Element image = new Element("image");
		Element imageTitle = new Element("title");
		imageTitle.setText("news.baidu.com");
		Element url = new Element("url");
		url.setText("http://img.baidu.com/img/logo-news.gif");
		image.addContent(imageTitle);
		image.addContent(url);
		channel.addContent(image);
		
		Element description = new Element("description");
		description.setText("<百度新闻订阅");
		channel.addContent(description);
		
		Element item = new Element("item");
		Element itemTitle = new Element("title");
		CDATA titleCdata = new CDATA("交通综合执法 用法治思维规范执法行为");
		itemTitle.addContent(titleCdata);
		item.addContent(itemTitle);
		Element pubDate = new Element("pubDate");
		CDATA pubDateCdata = new CDATA("2015-02-13T07:53:57.000Z");
		pubDate.addContent(pubDateCdata);
		item.addContent(pubDate);
		channel.addContent(item);
		
		rss.addContent(channel);
		//3.创建Format对象(通过其静态方法)
		Format format = Format.getCompactFormat();
		format.setEncoding("gb2312");//设置编码方式为gb2312
		format.setIndent("	");//设置缩进（此处为一个tab键）
		
		//4.创建一个XMLOutputter对象，并为其指定Format
		XMLOutputter outputter = new XMLOutputter(format);
		
		//5.调用XMLOutputter对象的output方法将文档写入到输出流
		outputter.output(document, new FileOutputStream("rssnews_jdom.xml"));
	}

}
